/*
 * Copyright (c) 2024 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <gtest/gtest.h>
#include <dlfcn.h>
#include <unordered_map>
#include <memory>
#include <test_utilities/test_base.h>
#include <mc/log.h>
#include <devmon/driver_abi.h>

#include "../../../drivers/accessor/accessor/accessor.h"
#include "../test_utils/root_object.h"

using namespace dev;
using namespace devmon;

namespace drivers {
namespace accessor {
namespace test {

class accessor_test_service : public mc::engine::service {
public:
    accessor_test_service(const std::string& name) : mc::engine::service(name) {
    }
};

class AccessorAbiTest : public mc::test::TestWithEngine {
public:
    static void SetUpTestSuite() {
        TestWithEngine::SetUpTestSuite();
        m_test_service = mc::make_shared<accessor_test_service>("bmc.kepler.test_accessor_abi");
        m_test_service->init();
        m_test_service->start();

        // 创建根对象
        m_root_object = root_object::create_root_object(m_test_service.get());

        load_driver();
    }

    static void TearDownTestSuite() {
        m_test_service->stop();
        m_root_object.reset();
        
        if (m_driver_handle != nullptr) {
            dlclose(m_driver_handle);
            m_driver_handle = nullptr;
        }
        
        m_test_service.reset();
        TestWithEngine::TearDownTestSuite();
    }

    void SetUp() override {
        // 测试用例之间无需特殊设置
    }

    void TearDown() override {
        // 测试用例之间无需特殊清理
    }

    static void load_driver() {
        m_driver_handle = dlopen("./opt/bmc/drivers/libAccessor.so", RTLD_LAZY);
        if (m_driver_handle == nullptr) {
            MC_THROW(mc::system_exception, "Failed to load Accessor driver: ${error}",
                     ("error", dlerror()));
        }
        
        register_device_driver_func func = reinterpret_cast<register_device_driver_func>(
            dlsym(m_driver_handle, "register_device_driver"));
        MC_ASSERT_THROW(func, mc::bad_function_call_exception,
                        "Failed to get register_device_driver function: ${error}",
                        ("error", dlerror()));

        device_driver_t* devices = nullptr;
        uint8_t devices_count = 0;
        status_t ret = func(&devices, &devices_count);
        MC_ASSERT_THROW(ret == STATUS_OK, mc::bad_function_call_exception,
                        "Failed to get device driver manager: ${error}", ("error", ret));

        m_devices.clear();
        m_devices.reserve(devices_count);
        for (uint8_t i = 0; i < devices_count; i++) {
            auto device_driver = std::make_shared<device_driver_t>(devices[i]);
            m_devices.emplace(device_driver->device_name, device_driver);
        }
    }

    mc::dict create_test_connector(uint8_t system_id = 1, uint8_t position = 1, uint8_t slot = 1) {
        return mc::dict{{"SystemId", system_id}, {"Position", position}, {"Slot", slot}};
    }

    mc::mutable_dict create_test_csr_object(const std::string& chip_path, uint32_t offset, 
                                           uint8_t size, uint32_t mask, uint8_t type) {
        return mc::mutable_dict{
            {"Chip", chip_path},
            {"Offset", offset},
            {"Size", size},
            {"Mask", mask},
            {"Type", type}
            // 注意：不包含Value字段，因为它有自定义的getter/setter逻辑
        };
    }

    static mc::shared_ptr<accessor_test_service> m_test_service;
    static std::unordered_map<std::string, std::shared_ptr<device_driver_t>> m_devices;
    static void* m_driver_handle;
    static root_object_ptr m_root_object;
};

mc::shared_ptr<accessor_test_service> AccessorAbiTest::m_test_service;
std::unordered_map<std::string, std::shared_ptr<device_driver_t>> AccessorAbiTest::m_devices;
void* AccessorAbiTest::m_driver_handle = nullptr;
root_object_ptr AccessorAbiTest::m_root_object;

// ========================= 驱动注册功能测试 =========================

TEST_F(AccessorAbiTest, register_device_driver_success) {
    EXPECT_EQ(m_devices.size(), 1);
    EXPECT_TRUE(m_devices.find("Accessor") != m_devices.end());
}

TEST_F(AccessorAbiTest, device_driver_structure_validation) {
    for (const auto& [device_name, device_driver] : m_devices) {
        EXPECT_FALSE(std::string(device_driver->device_name).empty());
        EXPECT_TRUE(device_driver->ctor != nullptr);
        EXPECT_TRUE(device_driver->init != nullptr);
        // start and stop functions should now be present for Accessor driver
        EXPECT_TRUE(device_driver->start != nullptr);
        EXPECT_TRUE(device_driver->stop != nullptr);
    }
}

// ========================= Accessor设备创建测试 =========================

TEST_F(AccessorAbiTest, create_accessor_success) {
    auto device_driver = m_devices["Accessor"];
    ASSERT_TRUE(device_driver != nullptr);

    auto device = device_driver->ctor(m_test_service.get(), "test_accessor");
    ASSERT_TRUE(device != nullptr);
    
    Accessor* accessor_device = static_cast<Accessor*>(device);
    EXPECT_TRUE(accessor_device != nullptr);
}

TEST_F(AccessorAbiTest, create_accessor_null_service) {
    auto device_driver = m_devices["Accessor"];
    ASSERT_TRUE(device_driver != nullptr);

    // 传入空服务指针应该返回nullptr
    auto device = device_driver->ctor(nullptr, "test_accessor");
    EXPECT_EQ(device, nullptr);
}

TEST_F(AccessorAbiTest, create_accessor_null_name) {
    auto device_driver = m_devices["Accessor"];
    ASSERT_TRUE(device_driver != nullptr);

    // 传入空名称应该返回nullptr
    auto device = device_driver->ctor(m_test_service.get(), nullptr);
    EXPECT_EQ(device, nullptr);
}

// ========================= Accessor设备初始化测试 =========================

TEST_F(AccessorAbiTest, init_accessor_success) {
    auto device_driver = m_devices["Accessor"];
    ASSERT_TRUE(device_driver != nullptr);

    auto device = device_driver->ctor(m_test_service.get(), "test_accessor_init");
    ASSERT_TRUE(device != nullptr);

    auto csr_object = create_test_csr_object("/test/MockChip", 0x100, 4, 0xFFFFFFFF, 1);
    auto connector = create_test_connector(1, 1, 1);

    status_t ret = device_driver->init(device, &csr_object, &connector);
    EXPECT_EQ(ret, STATUS_OK);
    
    // 验证属性设置
    Accessor* accessor_device = static_cast<Accessor*>(device);
    EXPECT_EQ(accessor_device->i_accessor.Offset.get_value(), 0x100);
    EXPECT_EQ(accessor_device->i_accessor.Size.get_value(), 4);
    EXPECT_EQ(accessor_device->i_accessor.Mask.get_value(), 0xFFFFFFFF);
    EXPECT_EQ(accessor_device->i_accessor.Type.get_value(), 1);
}

TEST_F(AccessorAbiTest, init_accessor_null_params) {
    auto device_driver = m_devices["Accessor"];
    ASSERT_TRUE(device_driver != nullptr);

    auto device = device_driver->ctor(m_test_service.get(), "test_accessor_null_init");
    ASSERT_TRUE(device != nullptr);

    // 测试空参数初始化
    status_t ret = device_driver->init(device, nullptr, nullptr);
    EXPECT_EQ(ret, STATUS_ERROR);
}

TEST_F(AccessorAbiTest, init_accessor_invalid_csr) {
    auto device_driver = m_devices["Accessor"];
    ASSERT_TRUE(device_driver != nullptr);

    auto device = device_driver->ctor(m_test_service.get(), "test_accessor_invalid_csr");
    ASSERT_TRUE(device != nullptr);

    // 创建无效的CSR对象（缺少必要字段）
    auto csr_object = mc::mutable_dict{{"InvalidField", "InvalidValue"}};
    auto connector = create_test_connector(1, 1, 1);

    status_t ret = device_driver->init(device, &csr_object, &connector);
    EXPECT_EQ(ret, STATUS_ERROR);
}

// ========================= Accessor设备启动停止测试 =========================

TEST_F(AccessorAbiTest, start_stop_accessor_success) {
    auto device_driver = m_devices["Accessor"];
    ASSERT_TRUE(device_driver != nullptr);

    auto device = device_driver->ctor(m_test_service.get(), "test_accessor_start_stop");
    ASSERT_TRUE(device != nullptr);

    auto csr_object = create_test_csr_object("/test/MockChip", 0x100, 4, 0xFFFFFFFF, 1);
    auto connector = create_test_connector(1, 1, 1);

    // 初始化
    status_t ret = device_driver->init(device, &csr_object, &connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 启动
    ret = device_driver->start(device);
    EXPECT_EQ(ret, STATUS_OK);

    // 停止
    ret = device_driver->stop(device);
    EXPECT_EQ(ret, STATUS_OK);
}

TEST_F(AccessorAbiTest, start_accessor_null_device) {
    auto device_driver = m_devices["Accessor"];
    ASSERT_TRUE(device_driver != nullptr);

    // 传入空设备指针应该返回错误
    status_t ret = device_driver->start(nullptr);
    EXPECT_EQ(ret, STATUS_ERROR);
}

TEST_F(AccessorAbiTest, stop_accessor_null_device) {
    auto device_driver = m_devices["Accessor"];
    ASSERT_TRUE(device_driver != nullptr);

    // 传入空设备指针应该返回错误
    status_t ret = device_driver->stop(nullptr);
    EXPECT_EQ(ret, STATUS_ERROR);
}

// ========================= Accessor属性验证测试 =========================

TEST_F(AccessorAbiTest, accessor_properties_validation) {
    auto device_driver = m_devices["Accessor"];
    ASSERT_TRUE(device_driver != nullptr);

    auto device = device_driver->ctor(m_test_service.get(), "test_accessor_properties");
    ASSERT_TRUE(device != nullptr);

    // 测试不同的属性值
    auto csr_object = create_test_csr_object("/test/TestChip", 0x200, 8, 0xFF00FF00, 2);
    auto connector = create_test_connector(1, 1, 1);

    status_t ret = device_driver->init(device, &csr_object, &connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 验证属性值
    Accessor* accessor_device = static_cast<Accessor*>(device);
    EXPECT_EQ(accessor_device->i_accessor.Chip.get_value(), "/test/TestChip");
    EXPECT_EQ(accessor_device->i_accessor.Offset.get_value(), 0x200);
    EXPECT_EQ(accessor_device->i_accessor.Size.get_value(), 8);
    EXPECT_EQ(accessor_device->i_accessor.Mask.get_value(), 0xFF00FF00);
    EXPECT_EQ(accessor_device->i_accessor.Type.get_value(), 2);
}

// ========================= Accessor边界值测试 =========================

TEST_F(AccessorAbiTest, accessor_boundary_values) {
    auto device_driver = m_devices["Accessor"];
    ASSERT_TRUE(device_driver != nullptr);

    auto device = device_driver->ctor(m_test_service.get(), "test_accessor_boundary");
    ASSERT_TRUE(device != nullptr);

    // 测试边界值
    auto csr_object = create_test_csr_object("/test/BoundaryChip", 0, 1, 0, 0);
    auto connector = create_test_connector(1, 1, 1);

    status_t ret = device_driver->init(device, &csr_object, &connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 验证边界值
    Accessor* accessor_device = static_cast<Accessor*>(device);
    EXPECT_EQ(accessor_device->i_accessor.Offset.get_value(), 0);
    EXPECT_EQ(accessor_device->i_accessor.Size.get_value(), 1);
    EXPECT_EQ(accessor_device->i_accessor.Mask.get_value(), 0);
    EXPECT_EQ(accessor_device->i_accessor.Type.get_value(), 0);
}

// ========================= Accessor完整生命周期测试 =========================

TEST_F(AccessorAbiTest, accessor_full_lifecycle) {
    auto device_driver = m_devices["Accessor"];
    ASSERT_TRUE(device_driver != nullptr);

    // 1. 创建设备
    auto device = device_driver->ctor(m_test_service.get(), "test_accessor_lifecycle");
    ASSERT_TRUE(device != nullptr);

    // 2. 初始化设备
    auto csr_object = create_test_csr_object("/test/LifecycleChip", 0x100, 4, 0xFFFFFFFF, 1);
    auto connector = create_test_connector(1, 1, 1);

    status_t ret = device_driver->init(device, &csr_object, &connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 3. 启动设备
    ret = device_driver->start(device);
    EXPECT_EQ(ret, STATUS_OK);

    // 4. 验证设备状态
    Accessor* accessor_device = static_cast<Accessor*>(device);
    EXPECT_EQ(accessor_device->i_accessor.Chip.get_value(), "/test/LifecycleChip");
    EXPECT_EQ(accessor_device->i_accessor.Offset.get_value(), 0x100);
    EXPECT_EQ(accessor_device->i_accessor.Size.get_value(), 4);

    // 5. 停止设备
    ret = device_driver->stop(device);
    EXPECT_EQ(ret, STATUS_OK);
}

} // namespace test
} // namespace accessor
} // namespace drivers 